const path = require("path");
const bp = require('body-parser');
// 引入自定义 mysql 工具
const mysql = require(path.join(__dirname, './mysql.js'));
// 引入 express
const express = require('express');
// 获取 express 实例对象
let app = express();

// 设置托管静态资源
app.use(express.static(path.join(__dirname, './public')));
// 处理 post 请求参数
app.use(bp.urlencoded({
    extended: false
}));

const days = () => {
    let now = new Date()
    let y = now.getFullYear()
    let m = now.getMonth() < 9 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1
    let d = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
    return '' + y + m + d
}

// 前端响应要创建订单的数据对象
app.get('/payinfo', (req, res) => {
    let data = req.query;
    // 做一个简单的商品判断
    if (data && (data.goodsName === '茴香大油条' || data.goodsName === '茴香小油条' || data.goodsName === '传统大油条' || data.goodsName === '传统小油条') && data.count && data.cost) {
        res.send(Object.assign(data, {
            code: 200,
        }));
    } else {
        res.setHeader('content-type', 'application/javascript');
        res.send('alert("信息有误，请重新尝试！！！")');
    }
})

// 获取创建订单的自定义模块
const createOrder = require(path.join(__dirname, './createOrder.js')).createOrder;
// 获取验签自定义模块
const checkSign = require(path.join(__dirname, './checkSign.js'));

// 生成订单请求
app.post('/createOrder', (req, res) => {
    req.body.pack_params = {
        payName: req.body.payName,
        goodsName: req.body.goodsName,
        price: req.body.price,
        count: req.body.count,
        cost: req.body.cost,
    }
    async function asyncCreate() {
        const result = await createOrder(req.body);
        res.send(result);
    }
    asyncCreate();
});

// 支付的信息展示
app.get('/payresult', (req, res) => {

    let sql = `select * from order_list where trade_no = '${req.query.trade_no}' AND days='${days()}' `

    mysql.selectSql(sql, (err, result) => {
        if (result.length) {
            result = result[0]
            let htmlStr = '';
            htmlStr += `<p class="pay-res">` + '名称' + ': ' + result.goods_name + '</p>'
            htmlStr += `<p class="pay-res">` + '总数量' + ': ' + result.count + ' 根</p>'
            htmlStr += `<p class="pay-res">` + '付款金额' + ': ' + result.total_amount + '元</p>'
            htmlStr += `<p class="pay-res"> 取餐号: <span style="font-size:30px;color:#d23536"> ${result.payName}</span></p>`
            htmlStr += '<h2 style="text-align:center;margin-top:30px">找收银核销后领取,谢谢惠顾! </h2>'
            htmlStr += '<p class="pay-res" style="text-align:center;margin-top:100px"><a style="text-decoration: none;color: #4782f7;" href="./index.html">返回首页</a> </p>'
            res.send(`<!doctype html>
            <html>
            
            <head>
                <meta charset="utf-8">
                <meta name="viewport"
                    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
                <meta http-equiv="X-UA-Compatible" content="ie=edge">
                <title>详情</title>
                <link rel="stylesheet" type="text/css" href="css/aui.css">
                <link rel="stylesheet" href="css/classify.css">
                <style>
                    html,
                    body {
                        height: 100%;
                        max-width: 640px;
                        margin: 0 auto;
                        padding:15px
                    }
    
                    .pay-res{
                        font-size:20px;
                        margin:5px;
                    }
            
                    .aui-bar-nav {
                        border: none;
                        background: #f5f5f5;
                    }
            
                    .main {
                        height: calc(100% - 4.5rem);
                    }
            
                    #tab1-con1 {
                        padding-bottom: 3rem;
                    }
            
                    #tab1-con1,
                    #tab1-con2 {
                        height: 100%;
                    }
            
                    .aui-tab {
                        border-bottom: solid 1px #eee;
                        background: #f5f5f5;
                        height: 2.25rem;
                    }
            
                    .aui-tab-item {
                        font-size: .75rem;
                        color: #666;
                        width: 25%;
                    }
            
                    .aui-tab-item.aui-active {
                        border: none;
                        color: #000;
                        position: relative;
                    }
            
                    .aui-tab-item.aui-active:after {
                        position: absolute;
                        left: 40%;
                        width: 20%;
                        height: 2px;
                        background: #00ae66;
                        content: '';
                        bottom: 0;
                    }
                </style>
            </head>
            <body>
            ${htmlStr}
            </body>
            </html>`
            );
        } else {
            res.send('无数据 <a style="text-decoration: none;color: #4782f7;" href="./index.html">返回首页</a>')
        }

    });

})

app.post('/notify', (req, res) => {
    // 输出验签结果
    async function checkResult(postData) {
        let result = await checkSign(postData);
        if (result) {
            let data = req.body;
            let goods = JSON.parse(data.passback_params);
            let sqlStr = `
            insert into order_list value("${data.out_trade_no}",
                "${data.trade_no}",
                "${goods.goodsName}",
                ${goods.count},
                ${data.total_amount},
                "支付成功",
                "${goods.payName}",
                "${days()}"
                );
            `;
            mysql.addSql(sqlStr)
            // 响应支付宝 success 处理成功，否则支付宝会一直定时发送异步通知
            res.end('success');
        }
    }
    checkResult(req.body);
})

// 查询订单接口
app.get('/getorder', (req, res) => {
    mysql.selectSql('select * from order_list', (err, result) => {
        result = Object.assign({
            code: 200,
            msg: '获取成功',
            list: JSON.stringify(result),
        })
        res.send(result);
    });
})

app.listen(9999, () => {
    console.log('server start with 9999');
})